package com.cat.slidingWindow;

/**
 * @author cat
 * @description https://leetcode.cn/problems/minimum-swaps-to-group-all-1s-together-ii/description/
 * @create 2025/7/27 19:16
 * @since JDK17
 */

public class Solution02 {
    public int minSwaps(int[] nums) {
        int sum = 0, total = 0, n = nums.length, ans = Integer.MAX_VALUE;
        for (int num : nums) {  // 算出1的总数
            total += num;
        }
        // 先不考虑环形
        for (int l = 0, r = 0, time = 0; l < n; l++) {
            while (time < total) {  // [l, r)的总和
                sum += nums[r];
                r = (r + 1) % n;
                time++;
            }
            ans = Math.min(ans, total - sum);
            sum -= nums[l];
            time--; // 少了一个
        }
        return ans;
    }
}
